package com.example.servlet.user;

import com.example.entity.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.MybatisUtil;
import com.example.utils.ThymeleafUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Objects;

@WebServlet("/user_profile_edit")
public class uProfileEditServlet extends HttpServlet {
    private UserService service;
    private SqlSession sqlSession;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new UserServiceImpl(sqlSession);
    }
    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Context context = new Context();
        if (req.getSession().getAttribute("account-failure") != null) {
            context.setVariable("account_failure", true);
            req.getSession().removeAttribute("account-failure");
        }
        if (req.getSession().getAttribute("phone-failure") != null) {
            context.setVariable("phone_failure", true);
            req.getSession().removeAttribute("phone-failure");
        }
        if (req.getSession().getAttribute("email-failure") != null) {
            context.setVariable("email_failure", true);
            req.getSession().removeAttribute("email-failure");
        }
        if (req.getSession().getAttribute("update-failure") != null) {
            context.setVariable("update_failure", true);
            req.getSession().removeAttribute("update-failure");
        }
        User user = (User) req.getSession().getAttribute("user");
        context.setVariable("name", user.getU_name());
        context.setVariable("sex", user.getSex());
        context.setVariable("ID_type", user.getID_type());
        context.setVariable("ID_card", user.getID_card());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        context.setVariable("birthday", formatter.format(user.getBirthday()));
        context.setVariable("phone_number", user.getU_phone());
        context.setVariable("account", user.getU_account());
        context.setVariable("password", user.getU_password());
        context.setVariable("grade", user.getGrade());
        context.setVariable("email", user.getEmail());
        context.setVariable("city", user.getCity());
        context.setVariable("user_id", user.getU_id());
        // 图片是否存在判断
        String imagePath = getServletContext().getRealPath("/static/images/" + user.getU_id() + ".jpg");
        File imageFile = new File(imagePath);
        boolean imageExists = imageFile.exists();
        context.setVariable("imageExists", imageExists);
        ThymeleafUtil.process("user_profile_edit.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sex = req.getParameter("olSex");
        String ID_card = req.getParameter("olIDcard");
        String ol_account = req.getParameter("olAccount");
        String ol_phone = req.getParameter("olPhone");
        String name = req.getParameter("rename");
        String phone = req.getParameter("rephone");
        String account = req.getParameter("reaccount");
        String password = req.getParameter("olPassword");
        String city = req.getParameter("recity");
        String ol_city = req.getParameter("olCity");
        try {
            if (service.isExistByAccount(account) == 1 && !Objects.equals(ol_account, account)) {
                req.getSession().setAttribute("account-failure", new Object());
                this.doGet(req, resp);
                return;
            }
            if (service.isExistByPhone(phone) == 1 && !Objects.equals(ol_phone, phone)) {
                req.getSession().setAttribute("phone-failure", new Object());
                this.doGet(req, resp);
                return;
            }
            if (service.updateUser(name, sex, ID_card, account, password, phone,city) == 1) {
                service.commit();
                // 移除session中的user对象
                req.getSession().removeAttribute("user");
                // 更新User对象的信息
                User updatedUser = service.getUser(account, password);
                // 将更新后的User对象设置到session中
                req.getSession().setAttribute("user", updatedUser);

                req.getSession().setAttribute("update-success", true);
                resp.sendRedirect("user_profile");
            } else {
                req.getSession().setAttribute("update-failure", new Object());
                throw new Exception("Failed to update user");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚事务
            service.rollback();
            this.doGet(req, resp);
        }
    }
}
